package util;

import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

/***
 * Hibernate Utility class with a convenient method to get Session Factory
 * object.
 *
 * @author desarrollo
 */
public class HibernateUtil {

    public static final SessionFactory sessionFactory;
    public static Session session;
    
    static {
        try {
            // Create the SessionFactory from standard (hibernate.cfg.xml) 
            // config file.
        	Configuration configuration = new Configuration();
        	configuration.configure();
        	ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
            sessionFactory = configuration.buildSessionFactory(serviceRegistry);;
        } catch (Throwable ex) {
            // Log the exception. 
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
    
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
    
    public static void iniciarSession(){
    	System.out.println("abriendo sesion");
    	session = sessionFactory.openSession();
    	System.out.println("sesion is open");
    }
    
    public static void cerrarSession(){
    	try{
    	System.out.println("cerrando sesion");
    	session.close();
    	System.out.println("sesion is closed");
    	}catch(Exception e){
    		System.out.println("Esta bien el error");
    	}
    }
}